package ua.kharkov.khpi.tarasenko.bach.web.tag;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import ua.kharkov.khpi.tarasenko.bach.core.Constant;
import ua.kharkov.khpi.tarasenko.bach.core.user.UserBean;
import ua.kharkov.khpi.tarasenko.bach.service.RecommendationService;
import ua.kharkov.khpi.tarasenko.bach.web.ui_beans.RecommendationBean;

public class InitRecommendationBeanTag extends SimpleTagSupport {

	private String recType = "nav";
	private String var = "var";

	@Override
	public void doTag() throws JspException, IOException {

		if (!recType.equals("nav") && !recType.equals("cart")) {
			throw new IllegalArgumentException("Illegal argument " + var + "="
					+ recType + ". Possible are 'nav' and 'cart'.");
		}

		PageContext pageContext = (PageContext) getJspContext();
		HttpServletRequest request = (HttpServletRequest) pageContext
				.getRequest();

		HttpSession session = request.getSession(false);
		UserBean ub = (UserBean) session
				.getAttribute(Constant.ATTRIBUTE_USER_BEAN);
		
		List<Integer> accessSequence = ub.getNavHistory();
		
		RecommendationService recService = new RecommendationService(((PageContext)getJspContext()).getServletContext());
		
		RecommendationBean rb = recService.getRecommendations(accessSequence, ub.getShoppingCart(), recType);			
		
		pageContext.setAttribute(var, rb);
	}

	public String getRecType() {
		return recType;
	}

	public void setRecType(String recType) {
		this.recType = recType;
	}

	public String getVar() {
		return var;
	}

	public void setVar(String var) {
		this.var = var;
	}
}
